package common.server.properties;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Properties 配置加载
 * @author Administrator
 * @version [版本号, 2018/1/5 0005]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
public final class PropertiesProperty {
    /**
     *
     */
    private static final Logger logger = LoggerFactory.getLogger(PropertiesProperty.class);

    /**
     *
     */
    public static final Map<String,Properties> PRO_MAP= new ConcurrentHashMap<>();


    /**
     * @param propertyFileName
     */
    public static Properties addProperties(String propertyFileName) {
        if(StringUtils.isNotBlank(propertyFileName)){
            if(PRO_MAP.containsKey(propertyFileName)){
                 return  PRO_MAP.get(propertyFileName);
            }
            try {
                Properties properties =  PropertiesLoaderUtils.loadAllProperties(propertyFileName);
                if(logger.isDebugEnabled()){
                    logger.debug("Load Properties [{}]={}",propertyFileName,properties);
                }
                PRO_MAP.put(propertyFileName,properties);
                return properties;
            } catch (IOException e) {
                logger.error("Load Properties ["+propertyFileName+"] Error:",e);
            }
        }
        return  null;
    }

    /**
     * @param propertyFileName
     * @return
     */
    public static Properties getProperties(String propertyFileName) {
        return PRO_MAP.get(propertyFileName);
    }

    /**
     *
     * @param propertyFileName
     * @param key
     * @return
     */
    public static String getProperty(String propertyFileName,String key) {
        return getProperties(propertyFileName).getProperty(key);
    }

    /**
     * 获取属性信息
     * @param key
     * @return
     */
    public static String getProperty(String key) {
        final String[] v = {""};
        PRO_MAP.values().forEach(properties->{
            if(properties.containsKey(key)){
                v[0] =  properties.getProperty(key);
            }
        });
        return v[0];
    }
}
